// 云函数入口文件
const cloud = require('wx-server-sdk')
const {
  WINTER_START_DATE,
  SUMMER_START_DATE
} = require('./config');
const ResponseDTO = require('./res');
const dayjs = require('dayjs');
const util = require('./util');
const axios = require('axios');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const TIME_TABLE = 'cloud-edu-timetable';
const USER = 'edu-cloud-users';
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //获取用户唯一身份ID
  let openid = wxContext.OPENID;
  /**获取基础的用户信息 */
  let userBase = null
  // 未绑定教务系统的返回未绑定标识 -- 可以返回自定义课表部分内容
  let queryRes = await db.collection(USER).where({
    openid: openid
  }).get();
  if (queryRes.data.length == 0) {
    console.warn('openid: %s 未绑定用户信息', openid);
  } else {
    userBase = queryRes.data[0];
  }
  //获取用户操作
  let action = event.action;
  //获取请求参数
  let params = event.params || {};
  // 获取默认参数
  let defaultParams = util.calcDefault();
  console.log(defaultParams)
  switch (action) {
    case 'getTable': {
      // 自动组装自定义课表信息
      /**优先检索数据 */
      if (userBase == null || userBase == undefined) {
        return ResponseDTO.succData({
          userInfo: null,
          tableData: []
        })
      }
      let timeQueryRes = await db.collection(TIME_TABLE).where({
        xh: userBase.bindId,
        studyYear: params.studyYear || defaultParams.studyYear,
        semester: params.semester || defaultParams.semester,
        week: params.week || defaultParams.week
      }).get();
      /**
       * 如果没有查询到内容,调用接口查询今日课表
       */
      if (timeQueryRes.data.length == 0) {
        /**初始化请求接口 */
        var EDU_API = 'http://jwgl.sdust.edu.cn/app.do?method=getKbcxAzc&xh=#{xh}&zc=#{zc}'
        EDU_API = EDU_API.replace('#{zc}', params.week || defaultParams.week);
        EDU_API = EDU_API.replace('#{xh}', userBase.bindId);
        let reqRes = await axios({
          method: "GET",
          url: EDU_API,
          headers: {
            "content-type": "application/json;charset=utf-8",
            "User-Agent": "Mozilla/5.0 (Linux; U; Mobile; Android 6.0.1;C107-9 Build/FRF91 )",
            "cache-control": "max-age=0",
            "token": userBase.token
          }
        })
        console.log(reqRes);
        if (reqRes.status == 200 && reqRes.data.token != '-1' && reqRes.data.token != -1) {
          //写入数据库
          db.collection(TIME_TABLE).add({
            data: {
              xh: userBase.bindId,
              studyYear: params.studyYear || defaultParams.studyYear,
              semester: params.semester || defaultParams.semester,
              week: params.week || defaultParams.week,
              timetableData: reqRes.data,
              xh: userBase.bindId,
              _createTime: dayjs().format('YYYY-MM-DD hh:mm:ss'),
              _updateTime: dayjs().format('YYYY-MM-DD hh:mm:ss')
            }
          })
          return ResponseDTO.succData({
            userInfo: userBase,
            tableData: reqRes.data
          })
        } else {
          console.log(reqRes)
          return ResponseDTO.wrap(500, "请求异常，请查看日志");
        }
      } else {
        return ResponseDTO.succData({
          userInfo: userBase,
          tableData: timeQueryRes.data[0].timetableData || []
        })
      }

      break;
    }
  }
}